package com.steadyoung.modelapp.rxretrofit.http;

import com.steadyoung.modelapp.entity.api.HttpResult;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by Administrator on 2017/9/7.
 * Email : steadyoung@foxmail.com
 * Auth  : wayne
 * Desc  : 网络请求结果统一处理
 */
class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
//        LogUtils.d("RetrofitLog","response>>" + response);
        //httpResult 只解析result字段
        HttpResult httpResult = gson.fromJson(response, HttpResult.class);
        //
       if (httpResult.getCode() != HttpService.SUCCESS_CODE) {
            throw new ApiException(httpResult.getCode(),httpResult.getMsg());
       }
//        return gson.fromJson(response, type);
        try{
            return gson.fromJson(response, type);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}
